# -*- coding: utf-8 -*-
import json

from django.db import models

from miniweixin.core.models import BkMiniWeixinUser


class VoteManager(models.Manager):
    def create_vote(self, title, desc, user, choices, is_mult, end_time):
        vote = self.model(title=title, desc=desc, user=user,
                          choices=json.dumps(choices), is_mult=is_mult, end_time=end_time)
        vote.save()
        return vote


class Vote(models.Model):
    """投票"""
    title = models.CharField(u"标题", max_length=255)
    desc = models.TextField(u"内容")
    user = models.ForeignKey(BkMiniWeixinUser)
    choices = models.TextField(u"投票选项", help_text=u"选项列表json串")
    is_mult = models.BooleanField(u"是否支持多选", default=False)
    create_time = models.DateTimeField(auto_now_add=True)
    end_time = models.DateTimeField(u"截止日期")

    objects = VoteManager()

    class Meta:
        verbose_name = u"投票"
        verbose_name_plural = u"投票"

    @property
    def choice_list(self):
        if self.choices:
            return json.loads(self.choices)
        return []


class VoteChoice(models.Model):
    """用户投票选项"""
    user = models.ForeignKey(BkMiniWeixinUser)
    vote = models.ForeignKey(Vote)
    choice = models.IntegerField(u"用户选择")
    create_time = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = u"用户选择的投票"
        verbose_name_plural = u"用户选择的投票"
